package ar.com.pragmatia.lanacion;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import ar.com.pragmatia.lanacion.data.AppData;
import ar.com.pragmatia.lanacion.data.Article;
import ar.com.pragmatia.lanacion.data.Order;
import ar.com.pragmatia.lanacion.data.OrderDetail;

public class MainOrderActivity extends LaNacionActivity {

	private EditText txtCode;
	private EditText txtName;
	private TableLayout tblOrders;
	private Dialog dialog;
	private Context appContext;
	private Date date;
	private static final int DATE_DIALOG_ID = 0;

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			date.setYear(year - 1900);
			date.setMonth(monthOfYear);
			date.setDate(dayOfMonth);
			updateTime();
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.orders_main);

		appContext = this;

		Button btnVisits = (Button) findViewById(R.id.btnOrders);
		if (btnVisits != null) {
			btnVisits.setPressed(true);
		}

		txtCode = (EditText) findViewById(R.id.txtCode);
		txtName = (EditText) findViewById(R.id.txtName);
		tblOrders = (TableLayout) findViewById(R.id.tblOrders);

		updateTime();
		txtCode.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					// txtCode.clearFocus();
					showDialog(DATE_DIALOG_ID);
				}
			}
		});

		txtCode.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				String text = getFilters();
				Order cl = new Order();
				Vector<AppData> v = cl.query(text);
				updateTable(tblOrders, v);
			}
		});

		txtName.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				String text = getFilters();
				Order cl = new Order();
				Vector<AppData> v = cl.query(text);
				updateTable(tblOrders, v);
			}
		});

		Order order = new Order();
		Vector<AppData> orders = order.find();
		appendRows(tblOrders, orders);

		OnClickListener addClient = new OnClickListener() {

			public void onClick(View v) {
				Intent newClientActivity = new Intent().setClass(
						getApplicationContext(), NewOrderActivity.class);
				startActivity(newClientActivity);

			}
		};

		Button btnAddClient = (Button) findViewById(R.id.btnAddClient);
		btnAddClient.setOnClickListener(addClient);
	}

	private String getFilters() {
		String filter = "SELECT orders.id, orders.seller_id, "
				+ "orders.client_id, " + "orders.created, orders.modified,"
				+ " orders.location, orders.order_type, "
				+ "orders.document_type FROM orders";
		String code = txtName.getText().toString();
		if (!code.isEmpty()) {
			filter += " INNER JOIN clients Client ON (orders.client_id = Client.id) WHERE Client.shop_name LIKE '%"
					+ code + "%'";
		}
		String name = txtCode.getText().toString();
		if (!name.isEmpty()) {
			if (!code.isEmpty()) {
				filter += " AND ";
			} else {
				filter += " WHERE ";
			}

			filter += "orders.created LIKE '" + name + "%'";
		}
		return filter;
	}

	private void addTableHeader(TableLayout table) {
		TableRow row = new TableRow(this);

		TextView c = new TextView(this);
		c.setText(getText(R.string.code));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.name));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.quantity));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.totaln));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.credit_available));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		row.setBackgroundColor(0xEEEEEEEE);

		table.addView(row, new TableLayout.LayoutParams());
	}

	private void updateTable(TableLayout table, Vector<AppData> orders) {
		table.removeAllViews();
		addTableHeader(table);
		appendRows(table, orders);
	}

	private void appendRows(TableLayout table, Vector<AppData> orders) {
		int rowSize = orders.size();
		for (int i = 0; i < rowSize; i++) {
			TableRow row = new TableRow(this);

			TextView c = new TextView(this);
			c.setText(((Order) orders.get(i)).getClient().getClientCode());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			c.setText(((Order) orders.get(i)).getClient().getShopName());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);

			Vector<AppData> orderDetails = ((Order) orders.get(i))
					.getOrderDetail();

			c.setText(new Integer(orderDetails.size()).toString());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			float total = 0;
			for (int j = 0; j < orderDetails.size(); j++) {
				total += new Float(
						((OrderDetail) orderDetails.get(j)).getPrice())
						* new Float(
								((OrderDetail) orderDetails.get(j))
										.getQuantity());
			}
			c.setText(new Float(total).toString());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			c.setText(((Order) orders.get(i)).getCreated());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			row.setTag(((Order) orders.get(i)).getId());

			row.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// v.getTag();

					dialog = new Dialog(appContext);
					dialog.setContentView(R.layout.order_details);

					Order clt = new Order();
					Order order = (Order) clt.find("WHERE id = " + v.getTag())
							.get(0);

					dialog.setTitle("");

					if (order != null) {
						dialog.setTitle(order.getClient().getShopName());

						TextView txtClientName = (TextView) dialog
								.findViewById(R.id.txtClientName);
						txtClientName.setText(order.getClient().getShopName());

						TextView txtDate = (TextView) dialog
								.findViewById(R.id.txtDate);
						txtDate.setText(order.getCreated());

						TableLayout detailsTable = (TableLayout) dialog
								.findViewById(R.id.tblOrderDetails);

						Vector<AppData> vec = order.getOrderDetail();
						float total = 0;
						for (int j = 0; j < vec.size(); j++) {
							TableRow row = new TableRow(appContext);

							TextView c = new TextView(appContext);
							c = new TextView(appContext);
							c.setText(((Article) ((OrderDetail) vec.get(j))
									.getArticle()).getCode());
							c.setPadding(3, 3, 3, 3);
							row.addView(c);

							c = new TextView(appContext);
							c.setText(((Article) ((OrderDetail) vec.get(j))
									.getArticle()).getName());
							c.setPadding(3, 3, 3, 3);
							row.addView(c);

							c = new TextView(appContext);
							c.setText(((OrderDetail) vec.get(j)).getQuantity());
							c.setPadding(3, 3, 3, 3);
							row.addView(c);

							c = new TextView(appContext);
							c.setText(((OrderDetail) vec.get(j)).getPrice());
							c.setPadding(3, 3, 3, 3);
							row.addView(c);

							float subtotal = (new Float(((OrderDetail) vec
									.get(j)).getPrice())).floatValue()
									* new Integer(((OrderDetail) vec.get(j))
											.getQuantity()).intValue();

							c = new TextView(appContext);
							c.setText(new Float(subtotal).toString());
							c.setPadding(3, 3, 3, 3);
							row.addView(c);

							row.setTag(j);

							total += subtotal;

							TextView txtTotal = (TextView) dialog
									.findViewById(R.id.txtTotal);

							txtTotal.setText(new Float(total).toString());

							detailsTable.addView(row,
									new TableLayout.LayoutParams(
											ViewGroup.LayoutParams.FILL_PARENT,
											ViewGroup.LayoutParams.FILL_PARENT,
											1.0f));
						}

					}

					// Button cancel = (Button) dialog
					// .findViewById(R.id.btnCancel);
					// cancel.setOnClickListener(new OnClickListener() {
					//
					// @Override
					// public void onClick(View v) {
					// dialog.dismiss();
					//
					// }
					// });
					dialog.show();

				}
			});

			table.addView(row, new TableLayout.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.FILL_PARENT, 1.0f));
		}
	}

	protected void updateTime() {
		if (date == null) {
			date = new Date();
		}
		// SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		txtCode.setText(sdf.format(date));
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener,
					date.getYear() + 1900, date.getMonth(), date.getDate());
		}
		return null;
	}
}
